package com.example.demo;

import java.io.*;
import java.lang.reflect.Method;
import java.util.Objects;

public class MyClassLoader extends ClassLoader{

    public static void main(String[] args) throws ClassNotFoundException {
       MyClassLoader myClassLoader = new MyClassLoader();
       Class<?> clazz = myClassLoader.loadClass("Hello");
       for(Method method: clazz.getMethods()){
           System.out.println(method);
       }
    }

    @Override
    protected Class<?> findClass(String className){
        byte[] bytecodes = new byte[0];
        try {
            bytecodes = resetBytecodes(getBytes(className+".xlass"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defineClass(className,bytecodes,0,bytecodes.length);
    }
    //读文件
    private byte[] getBytes(String fiename) throws IOException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fiename);
        int length = Objects.requireNonNull(inputStream).available();
        byte[] bytes = new byte[length];
        inputStream.read(bytes);
        return bytes;
    }
    //还原字节码
    private byte[] resetBytecodes(byte[] before){
       byte[] after = new byte[before.length];
       for(int i=0;i<before.length;i++){
           after[i] = (byte) (255-before[i]);
       }
       return after;
    }
}
